//
//  HYOUHomeMoreCollectionCell.m
//  BestGift
//
//  Created by 温晓宇 on 16/1/5.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "HYOUHomeMoreCollectionCell.h"
#import "HYOUHomeTableViewCell.h"
@interface HYOUHomeMoreCollectionCell ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic ,retain) HYOUBaseTableView *moreTableView;

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉

@property(nonatomic, copy) NSString *moreUrl;
@property(nonatomic, copy) NSString *url_string;

@end

@implementation HYOUHomeMoreCollectionCell
//-(void)dealloc{
//    [_allArray release];
//    [_delegate release];
//    [_titleId release];
//    [_moreTableView release];
//    [_moreUrl release];
//    [_url_string release];
//    [super dealloc];
//}
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubViews];
    }
    return self;
}
-(void)createSubViews{
    self.moreTableView = [[HYOUBaseTableView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, HEIGHT - 140) style:UITableViewStylePlain];
//    self.moreTableView.backgroundColor = [UIColor whiteColor];
    self.moreTableView.delegate = self;
    self.moreTableView.dataSource = self;
    [self.contentView addSubview:self.moreTableView];
//    [_moreTableView release];
    self.moreTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.moreTableView registerClass:[HYOUHomeTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.allArray = [NSMutableArray array];
}
-(void)setAllArray:(NSMutableArray *)allArray{
    if (_allArray != allArray) {
        [_allArray release];
        _allArray = [allArray retain];
    }
    [self.moreTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HYOUHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.model = self.allArray[indexPath.row];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HYOUOneCellModel *model = self.allArray[indexPath.row];
    [self.delegate showCellWebView:model.content_url Image:model.cover_image_url title:model.title];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}
-(void)setTitleId:(NSString *)titleId{
    if (_titleId != titleId) {
        [_titleId release];
        _titleId = [titleId retain];
    }
    [self.moreTableView reloadData];
//    NSLog(@"%@",self.titleId);
    
    NSString *url = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?generation=2&gender=2&limit=20&offset=0",self.titleId];
    self.moreUrl = url;
    
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    
}
#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block HYOUHomeMoreCollectionCell *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.moreTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 0;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.moreTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block HYOUHomeMoreCollectionCell *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.moreTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage += 20;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}





#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    //    NSString *url_string = [NSString stringWithFormat:@"https://api.weibo.com/2/friendships/friends.json?uid=5626008324&access_token=2.00klJkIGGZulFC50e2f524e40S8nlw&cursor=%ld&count=2",nextCursor];

    
    self.url_string = self.moreUrl;
//    NSLog(@"%ld",(unsigned long)self.url_string.length);
    if (self.url_string.length == 85 || self.url_string.length == 84 || self.url_string.length == 83) {
        NSString *next = [NSString stringWithFormat:@"%ld",(long)nextCursor];
        self.url_string = [self.url_string stringByReplacingCharactersInRange:NSMakeRange(self.url_string.length - 1, 1) withString:next];
        
    }else{
        NSString *next = [NSString stringWithFormat:@"%ld",(long)nextCursor];
        self.url_string = [self.url_string stringByReplacingCharactersInRange:NSMakeRange(self.url_string.length - 2, 2) withString:next];
    }
    NSLog(@"%@",self.url_string);
//    NSLog(@" page = %ld\n url = %@", self.nextPage, url_string);
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:self.url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.allArray removeAllObjects];
            self.url_string = self.moreUrl;
        }
        
        NSMutableDictionary *bigDic = responseObject;
        NSMutableDictionary *data = [bigDic objectForKey:@"data"];
        NSMutableArray *items = [data objectForKey:@"items"];
        for (NSDictionary *dic in items) {
            HYOUOneCellModel *model = [[HYOUOneCellModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
//            [[HYOUSingleton shareDataSingleton] insertHomeCellIntoTable:model];
            [self.allArray addObject:model];
//            [model release];
        }
        
        
        
        
        [self.moreTableView footerEndRefreshing];
        [self.moreTableView headerEndRefreshing];
        [self.moreTableView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
